﻿using System;
using System.Collections.Generic;
using System.Text;
using RS.DOM.Common;


namespace RS.DOM.Types
{
    public class Collections : Token
    {
        public Collections(Context context)
            : base(context)
        {
            base.TokenType = TokenType.Collections;
            this.Result = new List<Collection>();
        }

        public override Token Operation(Token token, OperationType type)
        {
            if (type == OperationType.Point)
            {
                return this.Point(token);
            }
            else if (type == OperationType.AddApply)
            {
                if (token.TokenType == TokenType.Collections)
                {
                    Collections op1 = this;
                    Collections op2 = (Collections)token;

                    foreach (Collection nc in op2.Result)
                        op1.Result.Add(nc);

                    return op1;
                }
                else
                {
                    return base.Operation(token, type);
                }
            }
            else
            {
                return base.Operation(token, type);
            }
        }

        public List<Collection> Result
        {
            get
            {
                return (List<Collection>)base.Result;
            }

            set
            {
                base.Result = value;
            }
        }

        public Token Point(Token token)
        {
            Token result = null;

            if (token.TokenType == TokenType.Number)
            {
                Collections op1 = this;
                Number op2 = (Number)token;

                if (op2.Result >= 0 && op2.Result < op1.Result.Count)
                {
                    result = this.Result[op2.Result];
                }
                else
                {
                    result = new Null(this.Context);
                }
            }

            return result;
        }

        public override string ToString()
        {
            //return "S";

            StringBuilder line = new StringBuilder();
            foreach (Collection nc in this.Result)
                line.Append(nc.ToString() + "\r\n");

            return line.ToString();
        }
    }
}